var form = layui.form,
    table = layui.table,
    $ = layui.jquery,
    upload = layui.upload,
    costCode = getQueryVariable("costCode"),
    costId = getQueryVariable("costId");

$('#editor-form').find('input,textarea,select').attr('disabled',true);
//表单初始值
if (costCode != "") {
    form.val("editor-form", {
        "registrationnumber": "进入查看详情",
    })
}
let costDetailData=[];
let costPaymentData=[];
let annexList=[];

let costApportionmentEntityList=[];
layer.ready(function () {
    //获取详情信息
    $.ajax({
        type:"POST",
        dataType:"json",
        contentType: 'application/json',
        data:costCode,
        async:false,
        url:"cost/getCostDetailByCostCode",
        success:function(res){
            if(res.status == 200){
                console.log(costCode)
                //主表信息赋值
                $("#code").val(res.data.code);
                if (res.data.costType==2){
                    $("#costType").val('间接费用');
                }else{
                    $("#costType").val('直接费用');
                }
                $("#currency").val(res.data.currencyName);
                $("#rmbRate").val(res.data.rmbRate);
                $("#usdRate").val(res.data.usdRate);
                $("#payee").val(res.data.payeeName);
                $("#bankName").val(res.data.bankName);
                $("#bankAccount").val(res.data.bankAccount);
                $('#accountName').val(res.data.accountName);
                $("#totalAmount").val(res.data.totalAmount);
                $("#createTime").val(res.data.createTime);
                $("#billCompanyName").val(res.data.billCompanyName);
                $("#operatorName").val(res.data.operatorName);
                $("#operatorCode").val(res.data.operatorCode);
                $("#description").val(res.data.description);

                //费用明细列表信息
                costDetailData = res.data.costDetailVOList;
                //费用付款明细列表信息
                costPaymentData = res.data.costPaymentList;
                //附件列表信息
                annexList = res.data.costAnnexVOList;
                //入库费用分摊集合
                costApportionmentEntityList=res.data.costApportionmenVOList;

                table.reload('attachmenttableid',{data : annexList});
                table.reload('maininformationtableid',{data : costDetailData});
                table.reload('expensesactuallypaidtableid',{data : costPaymentData});

                return false;
            }else {
                layer.msg(res.msg, {icon: 5});
            }
        }
    });

})





table.render({
    elem: '#maininformation',
    id: 'maininformationtableid',
    data: costDetailData,
    cols: [[
        {field:'invoiceCode', title:'发票号码',sort:true},
        {field: 'increaseCode',  title: '增票号',sort:true},
        {field: 'contractNo',title: '外销合同号',sort:true},
        {field:'stockNoStr', title:'采购合同号',sort:true},
        {field: 'feeName',  title: '费用名称', sort:true},
        {field: 'applicationAmount',  title: '申请金额', sort:true},
        {field: 'salesmanName',  title: '承担人员',sort:true},
        {field:'accountantName', title:'核算人员', sort:true},
        {field:'departmentName', title:'核算部门', sort:true},
        {field: 'specialDesc',  title: '特殊备注',sort:true},
        {field: 'costClassification',  title: '费用归类',sort:true},
        {field: 'billDate',  title: '单据日期', edit: 'text'},
    ]],
    limit: Number.MAX_VALUE,
    height: 380
});

table.render({
    elem: '#expensesactuallypaid'
    ,data:costPaymentData
    ,cols: [[
        {field:'createTime', title:'实付日期',sort:true,templet: "<div>{{layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss')}}</div>"}
        ,{field:'bankName', title:'付款银行',sort:true}
        ,{field:'bankAccount', title:'付款账号',sort:true}
        ,{field:'currencyName', title:'币种',sort:true}
        ,{field:'usdRate', title:'美金汇率',sort:true}
        ,{field:'totalCost', title:'实付金额',sort:true}
        ,{field:'remark', title:'支付费用备注',sort:true}
        ,{field:'operatorName', title:'操作员名称',sort:true}
    ]]
    ,id: 'expensesactuallypaidtableid'
    ,height: 380,
    limit: Number.MAX_VALUE,
});
let data0=[];
table.render({
    elem: '#warehousingcostsharing',
    id: 'warehousingcostsharingtableid',
    data: costApportionmentEntityList,
    cols: [[
        {field: 'billno',  title: '入库单号',sort:true},
        {field: 'instoreTimeStr',  title: '入库日期',sort:true},
        {field: 'warehouseName',  title: '仓库名称',sort:true},
        {field: 'apportionmentAmount',  title: '分摊金额',sort:true},
        {field: 'num', title: '数量',sort:true},
        {field: 'bulk', title: '体积', sort:true},
        {field: 'netWeight', title: '净重', sort:true},
        {field: 'grossWeight', title: '毛重', sort:true},
        {field: 'personName', title: '入库人', sort:true},
        {field: 'operatorName', title: '操作人', sort:true},
    ]],
    limit: Number.MAX_VALUE,
    height: 380
});

table.render({
    elem: '#breakdetail',
    id: 'breakdetailtableid',
    data: data0,
    cols: [[
        {field: 'invoicenumber',  title: '发票编号',sort:true},
        {field: 'contractno',  title: '采购单号',sort:true},
        {field: 'exportcontractno',  title: '外销合同号',sort:true},
        {field: 'splitamount',  title: '拆分金额',sort:true},
        {field: 'note',  title: '备注', sort:true}
    ]],
    limit: Number.MAX_VALUE,
    height: 380
});


//监听提交
form.on('submit(form-element)', function (data) {


        let datas=data.field;
        datas['annexReqs']=table.cache['attachmenttableid'];
        //1：新增，2：修改
        datas['setType']='2';
        datas['isViewFile']='isViewFile';//只是用来标记
        datas['id']=costId;
        $.ajax({
            type:"POST",
            dataType:"json",
            contentType: 'application/json',
            data:JSON.stringify(datas),
            url:"cost/add/register",
            success:function (res) {
                if(res.status==200){
                    layer.msg("保存成功", {icon: 6});
                    return false;
                }else {
                    layer.msg(res.data, {icon: 6});
                    return false;
                }

            }
        });
    
    return false;

})
//---附件
table.render({
    elem: '#attachment'
    , data: annexList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'fileName', title: '文件名', fixed: true}
        , {field: 'uploadTime', title: '上传日期', fixed: true}
        , {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'}
    ]]
    , id: 'attachmenttableid'
    , height: 380,
    limit: Number.MAX_VALUE,
});
let uploadListIns = upload.render({
    elem: '#uploadfile'
    , url: 'transfer/uploadFile'
    , field: "uploadify"
    , accept: 'file'
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">'
                , '<td>' + file.name + '</td>'
                , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                , '<td>等待上传</td>'
                , '<td>'
                , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                , '</td>'
                , '</tr>'].join(''));

            //单个重传
            tr.find('.demo-reload').on('click', function () {
                obj.upload(index, file);
            });

            //删除
            tr.find('.demo-delete').on('click', function () {
                delete files[index]; //删除对应的文件
                tr.remove();
                uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
            });

            $("#uploadlist").append(tr);
        });
    }
    , parseData: function(res){
        return {
            "code": res.status,
            "count": res.total,
            "data": res.data
        };
    }
    , done: function (res, index, upload) {
        let data = res.data;
        for(var i in data){
            if (data[i].status) { //上传成功
                annexList.push(data[i]);
                var tr = $("#uploadlist").find('tr#upload-' + index)
                    , tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);
        }
    }
    , error: function (index, upload) {
        var tr = $("#uploadlist").find('tr#upload-' + index)
            , tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});
table.on('toolbar(attachmenttable)', function (obj) {
    var checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {data:annexList}); //点击关闭刷新表格
                }
            });
            break;
    }
    ;
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        let xmlHttpRequest = new XMLHttpRequest();
        let url = "wjinfo/downloadfile2?filename=" + data.filePath;
        xmlHttpRequest.open('GET', url, true);
        //设置请求头
        xmlHttpRequest.setRequestHeader("Content-type", "application/json")
        xmlHttpRequest.responseType = "blob";
        xmlHttpRequest.send(null);

        xmlHttpRequest.onload = function() {
            let content = xmlHttpRequest.response;
            // 组装a标签
            let elink = document.createElement("a");

            //设置文件下载路径
            elink.download = decodeURIComponent(data.fileName);
            elink.style.display = "none";
            let blob = new Blob([content], { type: 'application/force-download' });

            //解决下载不存在文件的问题，根据blob大小判断
            if(blob.size==0){
                layer.msg('服务器没找到此文件，请联系管理员!');
            }else{
                elink.href = window.URL.createObjectURL(blob);
                document.body.appendChild(elink);
                elink.click();
                document.body.removeChild(elink);
            }

        }
    } else if (obj.event === 'del') {
        layer.confirm('确认删除?',
            confirmInfo(3,5), function (index) {
                obj.del();
                let id = data.id;
                for (var i = 0; i < annexList.length; i++) {
                    if (annexList[i].id == id) {
                        annexList.splice(i, 1); // 将使后面的元素依次前移，数组长度减1
                        i--; // 如果不减，将漏掉一个元素
                        break;
                    }
                }
                layer.msg("删除成功", {icon: 6});
                layer.close(index);
                table.reload('attachmenttableid', {data:annexList}); //ajax删除成功之后刷新表格
            });
    }
});
//提示信息渲染
function confirmInfo(icon, anim) {
    let data = {
        icon: icon,
        title: "提示",
        offset: "auto",
        skin: 'layui-layer-molv',
        anim: anim
    }
    return data;
}

//---操作日志
    table.render({
        elem: '#otherwarehouselog'
        , data: data0
        , cols: [[
            {field: 'operationtype', title: '操作类型', fixed: true}
            , {field: 'theoperator', title: '操作员'}
            , {field: 'operationdate', title: '操作日期'}
            , {field: 'modifythecontent', title: '修改内容'}
        ]]
        , id: 'logtableid'
        , height: 380
        // , limit: 30//显示的数量
        // , page: true
    });